//获取应用实例
const app = getApp();
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var utilCity = require('../../utils/cityData.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    locationCity: '北京市', //定位城市
    locationCityId: '201', //定位城市的Id  
    bizTypeGroup: [{ //机动车业务
        title: "机动车业务",
        child: [{
            BizTypeIcon: "icon-bulingjidongchehaopai",
            MasterBizTypeID: "1",
            BizTypeID: "1",
            BizTypeName: "补领机动车号牌",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-huanlingjidongchehaopai",
            MasterBizTypeID: "1",
            BizTypeID: "2",
            BizTypeName: "换领机动车号牌",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-shenlingmianjianbiaozhi",
            MasterBizTypeID: "1",
            BizTypeID: "3",
            BizTypeName: "申领免检标志",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-bulingmianjianbiaozhi",
            MasterBizTypeID: "1",
            BizTypeID: "6",
            BizTypeName: "补领检验合格标志",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-linshihaopaiercishenling",
            MasterBizTypeID: "1",
            BizTypeID: "5",
            BizTypeName: "临时号牌二次申领",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-biangengjidongchelianxifangshi",
            MasterBizTypeID: "1",
            BizTypeID: "4",
            BizTypeName: "变更机动车联系方式",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-gengduo",
            MasterBizTypeID: "1",
            BizTypeID: "-1",
            BizTypeName: "更多业务",
            CallBack: "addRegister"
          }
        ],
        colNum: 4
      },
      { //驾驶证页面
        title: "驾驶证业务",
        child: [{
            BizTypeIcon: "icon-qimanhuanzhengjiashizheng",
            MasterBizTypeID: "2",
            BizTypeID: "7",
            BizTypeName: "期满换领驾驶证",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-yishisunhuihuanlingjiashizheng",
            MasterBizTypeID: "2",
            BizTypeID: "8",
            BizTypeName: "遗失损坏换领驾驶证",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-chaolinghuanlingjiashizheng",
            MasterBizTypeID: "2",
            BizTypeID: "9",
            BizTypeName: "超龄换领驾驶证",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-zhuanruhuanlingjiashizheng",
            MasterBizTypeID: "2",
            BizTypeID: "10",
            BizTypeName: "转入换领驾驶证",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-yanqihuanlingjiashizheng",
            MasterBizTypeID: "2",
            BizTypeID: "11",
            BizTypeName: "延期换领驾驶证",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-yanqitijiaoshentizhengming",
            MasterBizTypeID: "2",
            BizTypeID: "12",
            BizTypeName: "延期提交身体证明",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-ziyuanjiangjihuanlingjiashizheng",
            MasterBizTypeID: "2",
            BizTypeID: "13",
            BizTypeName: "自愿降级换领驾驶证",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-ziyuanzhuxiaojiashizheng",
            MasterBizTypeID: "2",
            BizTypeID: "14",
            BizTypeName: "自愿注销驾驶证",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-shenlingjiashirenxinyongzhengming",
            MasterBizTypeID: "2",
            BizTypeID: "16",
            BizTypeName: "申领驾驶人信用证明",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-biangengjiashizhenglianxixinxi",
            MasterBizTypeID: "2",
            BizTypeID: "15",
            BizTypeName: "变更驾驶证联系方式",
            CallBack: "addRegister"
          },
          {
            BizTypeIcon: "icon-gengduo",
            MasterBizTypeID: "2",
            BizTypeID: "-1",
            BizTypeName: "更多业务",
            CallBack: "addRegister"
          }
        ],
        colNum: 4
      }
    ],
    modalHidden: true, //隐藏对话框
    modalMsg: '请先进行身份认证及视频认证', //提示用户进行身份以及视频认证
    sureText: '认证',
    currentTabIndex: 0, //当前被选中的菜单索引
    canNetOrder: false, //是否可以下单
    isAuthority: false //判断是否定位授权了，不授权不让下单
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let self = this;

    //微信分享调整
    wx.showShareMenu({
      withShareTicket: true
    })

    //授权
    app.addUserAuth(function(usr) {
      let isAuthority = self.data.isAuthority;
     // console.log("isAuthority:" + isAuthority)
      if (isAuthority) {
        if (usr.UserID <= 0 || usr.AuthLevel < 4) {
          wx.showModal({
            title: '认证',
            content: '用户未认证，请认证。',
            confirmText: '认证',
            success(res) {
              if (res.confirm) {
                self.navigateToAuth(usr);
              } else if (res.cancel) {
                //console.log('用户点击取消')
                //console.log('用户点击取消')
                self.setData({
                  isAuthority: false
                })
              }
            }
          });
        }
      }else{
        //首先进行定位授权查询
        self.isGetAuthority();
      }
    }, function(err) {

    });

  },
  /**
   * 生命周期函数--页面展示
   */
  onShow: function() {
    this.setData({
      locationCityId: app.locationInfo.cityId || "201",
      locationCity: app.locationInfo.cityName || '北京'
    });
    console.log(this.data.canNetOrder); 
  },
  /**
   * 查询是否获取了所需权限
   */
  isGetAuthority: function() {
    let self = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          //console.log('用户没有授权定位');
          //没有授权camera就先进行授权
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              //用户同意定位授权
              self.getLocation();
              self.setData({
                isAuthority: true,
                canNetOrder: true
              })
            },
            fail() {
              self.openConfirm();
              self.setData({
                isAuthority: false,
                canNetOrder: false
              })
            }
          });
        } else {
          //console.log('用户已经授权定位');
          //用户同意定位授权
          self.getLocation();
          self.setData({
            isAuthority: true
          })
        }
      },
      fail() {
        self.setData({
          isAuthority: false
        })
      }
    })
  },
  /**
   *  获取定位
   */
  getLocation: function() {
    let self = this;
    // 实例化API核心类
    let qqmapsdk = new QQMapWX({
      key: 'V73BZ-57ZKJ-MEZFX-FMFZW-J4HW5-KBBUP'
    });
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function(res) {
            if (res.status == 0) {
              self.getCityInfo(res.result.address_component);
              self.setData({
                locationCity: app.locationInfo.cityName, //定位城市
                locationCityId: app.locationInfo.cityId, //定位城市的Id
              });
              self.getBizTypes();
            } else {
              wx.showToast({
                title: '获取定位失败,请手动定位',
                icon: 'none',
                duration: 2000
              })
            }
          },
          fail: function(res) {
            wx.showToast({
              title: '获取定位失败,请手动定位',
              icon: 'none',
              duration: 2000
            })
          }
        });
      },
      fail: function() {
        wx.showToast({
          title: '获取定位失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  /**
   * 再次获取授权
   */
  openConfirm: function() {
    let self = this;
    wx.showModal({
      title: '提示',
      content: '检测到您没打开车管通的定位权限，会影响下单操作，是否去设置打开？',
      success(res) {
        if (res.confirm) {
          //console.log('用户点击确定');
          wx.openSetting({
            success: (res) => {
              //console.log(res);
              if (res.authSetting['scope.userLocation']) {
                //用户同意定位授权
                self.getLocation();
                self.setData({
                  isAuthority: true,
                  canNetOrder: true
                });
              } else {
                //用户拒绝定位授权
                self.setData({
                  isAuthority: false,
                  canNetOrder: false
                })
              }
            },
            fail: (e) => {
              //console.log(e);
              self.setData({
                isAuthority: false
              })
            }
          })
        } else if (res.cancel) {
          //console.log('用户点击取消');
          self.setData({
            isAuthority: false
          });
        }
      }
    })
  },
  /**
   * 认证跳转
   */
  navigateToAuth(usr) {
    if (usr.UserID <= 0) {
      wx.navigateTo({
        url: '/pages/liveAuthentication/sms/sms',
      })
    } else {
      //用户未认证-手机认证
      if (usr.AuthLevel == 0) {
        wx.navigateTo({
          url: '/pages/liveAuthentication/ocr/ocr',
        })
        //console.log('usr.AuthLevel0', usr.AuthLevel);
      } else if (usr.AuthLevel < 4) { //身份认证
        wx.navigateTo({
          url: '/pages/liveAuthentication/video/video',
        })
        //console.log('usr.AuthLevel4', usr.AuthLevel);
      }
    }
  },
  /**
   *  tab菜单切换
   */
  tabTap: function(e) {
    let self = this;
    let currentIndex = e.currentTarget.dataset.index;
    self.setData({
      currentTabIndex: currentIndex
    })
  },
  /**
   * 跳转页面
   */
  addRegister(e) {
    let self = this;
    let usr = app.userInfo;
    //已经获取授权
    if (usr.UserID <= 0 || usr.AuthLevel < 4) {
      wx.showModal({
        title: '认证',
        content: '用户未认证，请认证。',
        confirmText: '认证',
        success(res) {
          if (res.confirm) {
            self.navigateToAuth(usr);
          } else if (res.cancel) {
            //console.log('用户点击取消')
          }
        }
      });
      return;
    }

    let btype = e.currentTarget.dataset.btype;
    let urlpath = e.currentTarget.dataset.urlpath;
    let mtype = e.currentTarget.dataset.mtype;
    if (self.data.canNetOrder) {
      if (btype == "-1") {
        wx.navigateTo({
          url: '/pages/index/moreMenu/moreMenu?MasterBizType=' + mtype,
        });
      } else {
        self.getUnCompleteOrder(btype, urlpath);
      }
    } else {
      wx.showModal({
        title: '提示',
        content: '当前城市暂未开通，请手动选择办理城市',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/cityList/cityList',
            })
          } else if (res.cancel) {
            //console.log('用户点击取消')
          }
        }
      });
    }


    //console.log(e)
  },
  /**
   * 根据定位获取城市信息
   */
  getCityInfo(addr) {
    let self = this,
      isExits = false;
    let cityData = utilCity.cityData;
    for (let i = 0; i < cityData.length; i++) {
      if (cityData[i].value.replace('省', '') == addr.province.replace('省', '')) {
        let chds = cityData[i].childs;
        app.locationInfo.provinceId = cityData[i].id;
        app.locationInfo.provinceName = cityData[i].value;
        for (let j = 0; j < chds.length; j++) {
          if (chds[j].value.replace('市', '') == addr.city.replace('市', '')) {
            app.locationInfo.cityId = chds[j].id;
            app.locationInfo.cityName = chds[j].value;
            isExits = true;
            break;
          }
        }
      } else if (cityData[i].value.replace('市', '') == addr.province.replace('市', '')) {
        let chds = cityData[i].childs;
        if (chds[j].value.replace('市', '') == addr.city.replace('市', '')) {
          app.locationInfo.cityId = chds[j].id;
          app.locationInfo.cityName = chds[j].value;
          isExits = true;
          break;
        }
      }
      if (isExits) {
        break;
      }
    }
  },
  /**
   * 根据城市获取开通业务
   */
  getBizTypes() {
    let self = this;
  
    let url = app.apiBaseUrl + "/Common/GetIndexBizType";
    app.httpRequest({
      method: "GET",
      url: url,
      showLoading: true,
      data: {
        cityId: app.locationInfo.cityId
      },
      success: function(res) {
        let rdata = res.data;
        if (rdata.status == 0) {
          if (rdata.data.length < 1) {
            self.setData({
              canNetOrder: false
            });
            wx.showModal({
              title: '提示',
              content: '当前城市暂未开通，请手动选择办理城市',
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/cityList/cityList',
                  })
                } else if (res.cancel) {
                  //console.log('用户点击取消')
                }
              }
            })
          } else {
            self.setData({
              bizTypeGroup: rdata.data,
              canNetOrder: true
            });
          }

        } else {
          wx.showToast({
            title: '获取业务失败',
            icon: 'none',
            duration: 2000
          });
        }
      }
    });
  },
  /**
   * 跳转到城市
   */
  goToCityListTap() {
    wx.navigateTo({
      url: '/pages/cityList/cityList',
    })
  },
  /**
   * 获取未完成的订单
   */
  getUnCompleteOrder(btype, urlpath) {
    let self = this;

    let url = app.apiBaseUrl + "/RegOrder/GetOrderId";
    app.httpRequest({
      method: "GET",
      url: url,
      showLoading: true,
      data: {
        userId: app.userInfo.UserID,
        bizTypeId: btype
      },
      success: function(res) {
        let rdata = res.data;
        if (rdata.status == 0) {
          if (rdata.data < 1) {
            wx.navigateTo({
              url: '/pages/index/mainOperation/order/guide/guide?BizTypeID=' + btype + '&NavigateUrl=' + urlpath,
            });
          } else {
            wx.showModal({
              title: '提示',
              content: '用户存在未完成订单,是否查看',
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/index/mainOperation/order/orderDetails/orderDetails?OrderId=' + rdata.data,
                  })
                } else if (res.cancel) {
                  //console.log('用户点击取消')
                }
              }

            })
          }
        } else {

        }
      }
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return app.sh
  }
})